package com.kingyea.gradle.utils;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class FreeMarkerHelper {
	private static Configuration cfg;
	static {
		cfg = new Configuration();
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		cfg.setDefaultEncoding("utf-8");
		cfg.setEncoding(Locale.CHINA, "UTF-8");
		cfg.setNumberFormat("0");
	}
	
	public static void evalFreeMarker(String name, Map<String, Object> context, 
			InputStream inputStream, OutputStream outputStream,boolean replaceBreak) throws Exception{
		InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
		Template tpl = new  Template(name, reader, cfg);
		tpl.setEncoding("UTF-8");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
		tpl.process(context, writer);
		
		String str = new String(out.toByteArray(),"UTF-8");
		if(replaceBreak){
			str = str.replaceAll("\r\n", "\n");
		}
		IOUtils.copy(new ByteArrayInputStream(str.getBytes("UTF-8")), outputStream);
		outputStream.flush();
	}
	
	public static String evalFreeMarker(Map<String, Object> context, String input) throws Exception{
		StringReader reader = new StringReader(input);
		Template tpl = new  Template("name", reader, cfg);
		tpl.setEncoding("UTF-8");
		
		StringWriter writer = new StringWriter();
		tpl.process(context, writer);
		return writer.toString();
	}
}
